package com.xunmall.common.config;

import com.google.common.collect.Sets;
import com.xunmall.security.SecUser;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.security.oauth2.resource.PrincipalExtractor;
import org.springframework.boot.autoconfigure.security.oauth2.resource.UserInfoTokenServices;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;

import java.util.Map;

/**
 * @Author: WangYanjing
 * @Date: 2018/12/27 10:53
 * @Description:
 */
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    private static final String RESOURCE_ID = "banbu_v3";

    @Value("${security.oauth2.resource.user-info-uri:}")
    private String gateway;

    @Bean
    public UserInfoTokenServices userInfoTokenServices() {
        UserInfoTokenServices userInfoTokenServices = new UserInfoTokenServices(gateway, null);
        // 根据userinfo生成Principle
        userInfoTokenServices.setPrincipalExtractor(new GateWayPrincipalExtractor());
        return userInfoTokenServices;
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.resourceId(RESOURCE_ID);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().permitAll();
    }
}

class GateWayPrincipalExtractor implements PrincipalExtractor {
    @Override
    public Object extractPrincipal(Map<String, Object> map) {
        Map<String, Object> principal = (Map<String, Object>) map.get("principal");
        String uuid = (String) principal.get("uuid");
        String showName = (String) principal.get("showName");
        String mobile = (String) principal.get("mobile");
        boolean enabled = (boolean) principal.get("enabled");
        boolean credentialsNonExpired = (boolean) principal.get("credentialsNonExpired");
        boolean accountNonLocked = (boolean) principal.get("accountNonLocked");
        boolean accountNonExpired = (boolean) principal.get("accountNonExpired");

        SecUser user = new SecUser(uuid, mobile, "", "", showName,
                enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, Sets.newHashSet());
        return user;
    }

}